package com.ia.aistream.manager.operating.util.style;

import com.alibaba.fastjson.JSONObject;
import com.ia.aistream.common.exception.base.CustomException;
import com.ia.aistream.common.utils.StringUtils;
import com.ia.aistream.common.utils.UUID;
import com.ia.aistream.common.utils.spring.SpringUtils;
import com.ia.aistream.manager.operating.conf.DocMapConf;
import com.ia.aistream.manager.operating.conf.DocMessageConf;
import com.ia.aistream.manager.operating.util.convert.DocHandleBusiness;
import com.ia.aistream.manager.operating.util.tools.DocToolUtil;
import com.ia.aistream.manager.operating.util.tools.WmfToPngUtilTest2;
import com.ia.aistream.manager.operating.util.visio.PdfToPngUtil;
import com.ia.aistream.mapper.operating.DocIndexMapper;
import com.ia.aistream.model.operating.dto.*;
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.*;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.util.FileUtil;
import org.springframework.context.annotation.Scope;

import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/***
 * 获取Word文件的样式
 * @author XiaoYu
 */
@Slf4j
@Scope("prototype")
public class DocStyleUtil {
    // 声明十六进制
    private static char[] HEX_VOCABLE = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};



    /************************** 获取Word样式的方法 ***********************/



    /***
     * 获取单元格的样式
     * @param table
     * @param rows
     * @param cell
     * @return
     */
    public static JSONObject getColumnStyle(Table table, int rows, int cell) throws UnsupportedEncodingException {
        // 获取行合并
        Integer rowsMerge = DocTableStyle.getRowsMerge(table, rows, cell);
        // 获取表格的最大行
//        int tableMaxCol = getTableMaxCol(table);
        // 获取列合并
        int colsMax = DocTableStyle.getColsMerge(table, rows, cell, 5);
        ColumnStyle columnStyle = DocStyleUtil.tableCellStyle(table.getRows().get(rows).getCells().get(cell));
        if(columnStyle==null) {
            return null;
        }
        columnStyle.getTdInfo().setRowMerge(rowsMerge);
        columnStyle.getTdInfo().setColMerge(colsMax);
        return (JSONObject)JSONObject.toJSON(columnStyle);
    }

    public static JSONObject getTitleColumnStyle(Table table, int rows, int cell, int par) throws UnsupportedEncodingException {

        // 获取表格的最大行
//        int tableMaxCol = getTableMaxCol(table);
        // 获取列合并
        ColumnStyle columnStyle = DocStyleUtil.titleTableCellStyle(table.getRows().get(rows).getCells().get(cell), par);
        if(columnStyle==null) {
            return null;
        }
        columnStyle.getTdInfo().setRowMerge(1);
        columnStyle.getTdInfo().setColMerge(1);
        return (JSONObject)JSONObject.toJSON(columnStyle);
    }

    /***
     * 获取附录表格的样式
     * @param table
     * @param rows
     * @param cell
     * @return
     * @throws UnsupportedEncodingException
     */
    public static JSONObject getAppendixColumnStyle(Table table, int rows, int cell) throws UnsupportedEncodingException {
        // 获取行合并
        Integer rowsMerge = DocTableStyle.getRowsMerge(table, rows, cell);
        // 获取表格的最大行
        int tableMaxCol = getTableMaxCol(table);
        // 获取列合并
        int colsMax = DocTableStyle.getColsMerge(table, rows, cell, tableMaxCol);
        ColumnStyle columnStyle = DocStyleUtil.tableCellStyle(table.getRows().get(rows).getCells().get(cell));
        if(columnStyle==null) {
            return null;
        }
        columnStyle.getTdInfo().setRowMerge(rowsMerge);
        columnStyle.getTdInfo().setColMerge(colsMax);
        return (JSONObject)JSONObject.toJSON(columnStyle);
    }
    /***
     * 获取附录中的单元格样式
     * @param table
     * @param rows
     * @param cell
     * @param colMax
     * @return
     */
    public static JSONObject getAppendixColumnStyle(Table table, int rows, int cell, int colMax) throws UnsupportedEncodingException {

        // 获取行合并
        Integer rowsMerge = DocTableStyle.getRowsMerge(table, rows, cell);
        // 获取列合并
        Integer colsMerge = DocTableStyle.getColsMerge(table, rows, cell, colMax);
        ColumnStyle columnStyle = DocStyleUtil.tableCellStyle(table.getRows().get(rows).getCells().get(cell));
        if(columnStyle==null) {
            return null;
        }
        columnStyle.getTdInfo().setColMerge(colsMerge);
        columnStyle.getTdInfo().setRowMerge(rowsMerge);
        return (JSONObject)JSONObject.toJSON(columnStyle);
    }


    /** 判断是否为标题  **/
    public static int isTitle(Paragraph paragraph){
        String content = paragraph.getText().trim();

        String listText = paragraph.getListText().trim();
        String trim = listText + "  " + content;
        trim = trim.replace("．", ".").trim();
        if(StringUtils.isEmpty(trim)){
            return 0;
        }
        return getNum(trim);
    }

    public static void main(String[] args) {
        String s ="0.4ppm＜Li＜3.5ppm";
        System.out.println(getNum(s));
    }
    /***
     * 内容
     * @param msg
     * @return
     */
    public static int getNum(String msg){
        String sum = "";

        int i;
        for (i=0; i<msg.length(); i++){
            if(msg.charAt(i)>='0' && msg.charAt(i)<='9'){
                sum += msg.charAt(i);
            }else if(msg.charAt(i)=='.'){
                sum += msg.charAt(i);
            }else{
                break;
            }
        }
        if(i>=msg.length()){
            return 0;
        } else if(!sum.contains(".") && msg.charAt(i)!=' ' && !msg.startsWith("附录") ){
            return 0;
        } else if (!msg.startsWith("附录") && DocHandleBusiness.isLetter(msg.charAt(i))){
            return 0;
        }
        if(msg.startsWith("附录")){
            return 2;
        }
        int len = sum.length();
        if(msg.contains(".")){
            len = msg.indexOf(".");
        }
        if(StringUtils.isEmpty(sum) || len>2){
            return 0;
        }
        String[] split = sum.split("\\.");
        if(split.length>2){
            return 0;
        }
        if (!sum.contains(".")){
            return 1;
        }
        if(sum.lastIndexOf(".")==sum.length()-1){
            return 1;
        }
        if(sum.lastIndexOf(".")<sum.length()-1 && sum.lastIndexOf(".")>0){
            return 2;
        }
        return 0;
    }
    /** 判断是否为标题  **/
//    public static int isTitle(Paragraph paragraph){
//
//        String styleName = paragraph.getStyleName().trim();
//
//        String content = paragraph.getText().trim();
//
//        String listText = paragraph.getListText();
//        String trim = listText + "  " + content;
//        trim = trim.trim();
//        trim = trim.replace("．", ".");
//        if(StringUtils.isEmpty(trim)){
//            return 0;
//        }
//        String vPattern ="^\\d{1,2}\\.\\d*\\s{1,2}.*$";
//        Pattern vR = Pattern.compile(vPattern);
//        Matcher vM = vR.matcher(trim);
//        if(styleName.startsWith("章节标题") || styleName.contains("CharChar") || vM.matches() || trim.startsWith("附录")){
//
//            // 判断是否只有一个标题
//            if(isOnlyNum(listText)){
//                return 1;
//            }
//            if(!isStartNum(trim) || isTwoLevelTitle(listText)){
//                return 0;
//            }
//            if(isTitleLevel(listText) || isTitleLevel(trim)){
//                return 1;
//            }else{
//                return 2;
//            }
//        }
//        return 0;
//    }

    /**
     * 获取规程修改跟踪的样式
     * @param tableCell
     * @return
     */
    public static ColumnStyle revStyle(TableCell tableCell){
        // 列样式
        ColumnStyle columnStyle = new ColumnStyle();
        // 创建TD对象
        TdInfo tdInfo = new TdInfo();
        // 记录文件对象
        List<TextInfo> textInfoList = new ArrayList<>();
        // 设置列的宽度
        tdInfo.setWidth(DocTableStyle.getCellWidth(tableCell));
        // 设置对齐方式
        tdInfo.setAlign(tableCell.getParagraphs().get(0).getFormat().getHorizontalAlignment().toString());

        columnStyle.setTdInfo(tdInfo);

        // 获取单元格的所有段落
        int count = tableCell.getParagraphs().getCount();
        for(int c=0; c<count; c++){

            // 获取段落
            Paragraph paragraph = tableCell.getParagraphs().get(c);

            // 获取段落内容
            String trim = paragraph.getText().trim();

            if(StringUtils.isEmpty(trim)){
                continue;
            }

            // 获取段落的对象数获取内容
            int parCount = paragraph.getChildObjects().getCount();
            String listText = paragraph.getListText().trim();

            // 遍历对象数量
            for(int i=0; i<parCount; i++){

                DocumentObject documentObject = paragraph.getChildObjects().get(i);
                if(documentObject instanceof TextRange){
                    // 内容样式
                    TextInfo textInfo = new TextInfo();

                    TextRange range = (TextRange) documentObject;
                    String content = range.getText().trim();

                    // 内容为空则跳过
                    if(StringUtils.isEmpty(content) && StringUtils.isEmpty(listText)){
                        continue;
                    }
                    if(i==0 && !StringUtils.isEmpty(listText)){
                        textInfo.setListContent(listText);
                        textInfo.setListFontName("Times New Roman");
                        textInfo.setFontSize(paragraph.getListFormat().getCurrentListLevel().getCharacterFormat().getFontSize());
                    }

                    // 处理特殊字符
                    content = DocToolUtil.handleSpecialData(content, range);
                    // 处理换行情况
                    if(count > 1 && c!=count-1 &&(i==parCount-1)){
                        content = content+"<br />";
                    }else {
                        if(content.equals("&ensp;")){
                            // 记录文字内容
                            continue;
                        }
                    }
                    // 给对象属性赋值
                    assignmentTextInfo(textInfo, content, range);
                    // 设置文字字体
                    textInfo.setFontName("宋体");
                    textInfoList.add(textInfo);
                }
            }
        }

        columnStyle.setTextInfoList(textInfoList);
        return columnStyle;
    }

    public static ColumnStyle titleTableCellStyle(TableCell tableCell, int c) throws UnsupportedEncodingException {

        // 列样式
        ColumnStyle columnStyle = new ColumnStyle();
        // 创建TD对象
        TdInfo tdInfo = new TdInfo();
        // 记录文件对象
        List<TextInfo> textInfoList = new ArrayList<>();
        // 设置列的宽度
        float cellWidth = DocTableStyle.getCellWidth(tableCell);
        // 处理列宽的问题
        if(cellWidth<1){
            return null;
        }
        tdInfo.setWidth(cellWidth);
        // 设置对齐方式
        tdInfo.setAlign(tableCell.getParagraphs().get(c).getFormat().getHorizontalAlignment().toString());

        // 设置单元格属性
        columnStyle.setTdInfo(tdInfo);

        int count1 = tableCell.getChildObjects().get(0).getChildObjects().getCount();
        for (int i=0; i<count1; i++){
            DocumentObject documentObject = tableCell.getChildObjects().get(0).getChildObjects().get(i);
            // 处理特殊符号
            if(documentObject instanceof Symbol){
                Symbol symbol = (Symbol) documentObject;
                textInfoList.add(assignmentSymbol(symbol));
            }
        }


            String encode = null;
            String fontName = null;
            boolean listFlag = true;
            // 获取段落
            Paragraph paragraph = tableCell.getParagraphs().get(c);

            // 获取段落内容
            String trim = paragraph.getText();
            // 获取列表标题样式
            String listText = paragraph.getListText();

            // 对列表数据进行编码
            if(!StringUtils.isEmpty(listText)){
                try{
                    encode = URLEncoder.encode(listText, "utf-8");
                    fontName = paragraph.getListFormat().getCurrentListLevel().getCharacterFormat().getFontName();
                }catch(UnsupportedEncodingException e){
                    log.error("符号编码失败...");
                }
            }

            // 获取段落的对象数获取内容
            int parCount = paragraph.getChildObjects().getCount();

            // 遍历对象数量
            for(int i=0; i<parCount; i++){

                DocumentObject documentObject = paragraph.getChildObjects().get(i);
                // 判断文本类型
                if(documentObject instanceof TextRange) {
                    boolean flag = true;
                    TextRange range = (TextRange) documentObject;
                    // 内容样式
                    TextInfo textInfo = new TextInfo();
                    String content = range.getText();
                    // 处理下划线的情况
                    if(paragraph.get(i).getCharacterFormat().getUnderlineStyle().toString().equals("Single")){
                        if(textInfoList.size()>0 && textInfoList.get(textInfoList.size()-1).getUnderLine()!=null &&
                                StringUtils.isEmpty(textInfoList.get(textInfoList.size()-1).getContent())){

                            continue;
                        }
                        // 处理下划线还是空格
                        if (StringUtils.isEmpty(content)){
                            flag = false;
                            textInfo.setUnderLine(1);
                        }else{
                            textInfo.setUnderLine(2);
                        }
                    }
                    if(flag){
                        // 将内容特殊数据进行处理
                        content = DocToolUtil.handleSpecialData(content, range);
                    }else{
                        content = content.replace(" ", "");
                    }

                    // 处理ListText数据的编码问题
                    if(listFlag && !StringUtils.isEmpty(encode)){
                        listFlag = false;
                        textInfo.setListContent(encode);
                        textInfo.setListFontName(fontName);
                        textInfo.setFontSize(paragraph.getListFormat().getCurrentListLevel().getCharacterFormat().getFontSize());
                    }



                    // 给对象属性赋值
                    assignmentTextInfo(textInfo, content, range);
                    textInfoList.add(textInfo);
                }else{
                    if(i==parCount-1){
                        TextInfo textInfo = new TextInfo();
                        textInfo.setContent("<br />");
                        textInfoList.add(textInfo);
                    }
                }
            }

            // 列表的数据
            if(!StringUtils.isEmpty(listText) && parCount==0){
                TextInfo textInfo = new TextInfo();
                textInfo.setListContent(encode);
                textInfo.setListFontName(fontName);
                textInfo.setFontSize(paragraph.getListFormat().getCurrentListLevel().getCharacterFormat().getFontSize());
                textInfoList.add(textInfo);
            }


        columnStyle.setTextInfoList(textInfoList);
        return columnStyle;
    }

    /***
     * 获取单元格列的样式
     * @param tableCell
     * @return
     */
    public static ColumnStyle tableCellStyle(TableCell tableCell) throws UnsupportedEncodingException {

        // 列样式
        ColumnStyle columnStyle = new ColumnStyle();
        // 创建TD对象
        TdInfo tdInfo = new TdInfo();
        // 记录文件对象
        List<TextInfo> textInfoList = new ArrayList<>();
        // 设置列的宽度
        float cellWidth = DocTableStyle.getCellWidth(tableCell);
        // 处理列宽的问题
        if(cellWidth<1){
            return null;
        }
        tdInfo.setWidth(cellWidth);
        // 设置对齐方式
        tdInfo.setAlign(tableCell.getParagraphs().get(0).getFormat().getHorizontalAlignment().toString());

        // 设置单元格属性
        columnStyle.setTdInfo(tdInfo);

//        int count1 = tableCell.getChildObjects().get(0).getChildObjects().getCount();
//        for (int i=0; i<count1; i++){
//            DocumentObject documentObject = tableCell.getChildObjects().get(0).getChildObjects().get(i);
//            // 处理特殊符号
//            if(documentObject instanceof Symbol){
//                Symbol symbol = (Symbol) documentObject;
//                textInfoList.add(assignmentSymbol(symbol));
//            }
//        }

        // 获取单元格的所有段落
        int count = tableCell.getParagraphs().getCount();
        for(int c=0; c<count; c++){
            String encode = null;
            String fontName = null;
            boolean listFlag = true;
            // 获取段落
            Paragraph paragraph = tableCell.getParagraphs().get(c);

            // 获取段落内容
            String trim = paragraph.getText();
            // 获取列表标题样式
            String listText = paragraph.getListText();
            //内容为空则继续下一次循环
            if(StringUtils.isEmpty(trim) && StringUtils.isEmpty(listText) && paragraph.getChildObjects().getCount()==0){
                continue;
            }
            // 对列表数据进行编码
            if(!StringUtils.isEmpty(listText)){
                try{
                    encode = URLEncoder.encode(listText, "utf-8");
                    fontName = paragraph.getListFormat().getCurrentListLevel().getCharacterFormat().getFontName();
                }catch(UnsupportedEncodingException e){
                    log.error("符号编码失败...");
                }
            }

            // 获取段落的对象数获取内容
            int parCount = paragraph.getChildObjects().getCount();

            // 遍历对象数量
            for(int i=0; i<parCount; i++){

                DocumentObject documentObject = paragraph.getChildObjects().get(i);
                // 判断文本类型
                if(documentObject instanceof TextRange) {
                    boolean flag = true;
                    TextRange range = (TextRange) documentObject;
                    // 内容样式
                    TextInfo textInfo = new TextInfo();
                    String content = range.getText();
                    // 处理下划线的情况
                    if(paragraph.get(i).getCharacterFormat().getUnderlineStyle().toString().equals("Single")){
                        if(textInfoList.size()>0 && textInfoList.get(textInfoList.size()-1).getUnderLine()!=null &&
                                StringUtils.isEmpty(textInfoList.get(textInfoList.size()-1).getContent())){
                            if(count > 1 && c!=count-1 &&(i==parCount-1)){
                                textInfo.setContent("<br />");
//                                textInfo.setFontSize(paragraph.getStyle().getCharacterFormat().getFontSize());
                                textInfoList.add(textInfo);
                            }
                            continue;
                        }
                        // 处理下划线还是空格
                        if (StringUtils.isEmpty(content)){
                            flag = false;
                            textInfo.setUnderLine(1);
                        }else{
                            textInfo.setUnderLine(2);
                        }
                    }
                    if(flag){
                        // 将内容特殊数据进行处理
                        content = DocToolUtil.handleSpecialData(content, range);
                    }else{
                        content = content.replace(" ", "");
                    }

                    // 处理ListText数据的编码问题
                    if(listFlag && !StringUtils.isEmpty(encode)){
                        listFlag = false;
                        textInfo.setListContent(encode);
                        textInfo.setListFontName(fontName);
                        textInfo.setFontSize(paragraph.getListFormat().getCurrentListLevel().getCharacterFormat().getFontSize());
                    }

                    // 处理换行情况
                    if(count > 1 && c!=count-1 &&(i==parCount-1)){
                        content = content+"<br />";
                    }

                    // 给对象属性赋值
                    assignmentTextInfo(textInfo, content, range);
                    textInfoList.add(textInfo);
                }else if(documentObject instanceof Symbol){
                    Symbol symbol = (Symbol) documentObject;
                textInfoList.add(assignmentSymbol(symbol));
                } else{
                    if(i==parCount-1){
                        TextInfo textInfo = new TextInfo();
                        textInfo.setContent("<br />");
                        textInfoList.add(textInfo);
                    }
                }
            }

            // 列表的数据
            if(!StringUtils.isEmpty(listText) && parCount==0){
                TextInfo textInfo = new TextInfo();
                textInfo.setListContent(encode);
                textInfo.setListFontName(fontName);
                textInfo.setFontSize(paragraph.getListFormat().getCurrentListLevel().getCharacterFormat().getFontSize());
                textInfoList.add(textInfo);
            }
        }

        columnStyle.setTextInfoList(textInfoList);
        return columnStyle;
    }

    /**
     * 获取段落的样式内容
     * 2.26 添加判断的角标配置
     * 3.3 添加图片获取规则
     * 3.4 添加图片转换失败后的验证
     * @param paragraph
     * @param fid 表示文件的id
     * @param titleName 表示最近的标题
     * @return
     */
    public static Map<String, Object> getParagraphStyle(Paragraph paragraph, String filePath, int imgNum, Long fid, String titleName) throws Exception {

        String ext = filePath.substring(filePath.lastIndexOf(".")+1);
        Map<String, Object> map = new HashMap<>();
        ParagraphTextStyle paragraphStyle = new ParagraphTextStyle();
        PgInfo pgInfo = new PgInfo();
        pgInfo.setPgAlign(paragraph.getFormat().getHorizontalAlignment().toString());
        // 设置页边距
        pgInfo.setPaddingWidth(getParagraphMargins(paragraph));
        // 获取该段落的对象数
        int charCount = paragraph.getChildObjects().getCount();
        boolean gsFlag = false;
        boolean listFlag = true;
        // 记录列表数据样式
        String listText = paragraph.getListText().trim();
        String trim = paragraph.getText().trim();
        boolean imgFlag = true;
        // 记录段落的样式
        List<TextInfo> textInfoList = new ArrayList<>();

        // 记录图片对象
        String imgStr = "";
        for(int i=0; i<charCount; i++) {

            boolean convertFlag = false;
            // 内容样式
            TextInfo textInfo = new TextInfo();

            if(listFlag && !StringUtils.isEmpty(listText)){
                listFlag = false;
                textInfo.setListContent(URLEncoder.encode(listText, "utf-8"));
                textInfo.setListFontName(paragraph.getListFormat().getCurrentListLevel().getCharacterFormat().getFontName());
                textInfo.setFontSize(paragraph.getListFormat().getCurrentListLevel().getCharacterFormat().getFontSize());
            }

            ParagraphBase paragraphBase = paragraph.get(i);
            if(paragraphBase instanceof DocOleObject){
                DocOleObject docOleObject = (DocOleObject)paragraphBase;
                String objectType = docOleObject.getObjectType();
                // 判断是否为公式
                if(objectType.startsWith("Equation")){
                    gsFlag = true;
                }else if(objectType.startsWith("Visio")){
                    imgFlag = false;
                    String visioPath = saveVisioFile(docOleObject, filePath, ext, titleName);
                    String[] split = visioPath.split("%F%G%F");

                    textInfo.setImgAddress(split[1]);
                    textInfo.setVisioAddress(split[0]);
                    textInfo.setImgWidth(docOleObject.getWidth());
                    textInfo.setImgHeight(docOleObject.getHeight());
                    textInfo.setImgFlag(2);
                }
            }else if (paragraphBase instanceof TextRange) {
                boolean flag = true;
                // 获取段落对象
                TextRange range = (TextRange) paragraphBase;
                String content = range.getText();

                if(paragraph.get(i).getCharacterFormat().getUnderlineStyle().toString().equals("Single")){
                    if(textInfoList.size()>0){
                        TextInfo textInfo1 = textInfoList.get(textInfoList.size() - 1);
                        if(textInfo1.getUnderLine()!=null && StringUtils.isEmpty(textInfo1.getContent())){
                            continue;
                        }
                    }
                    if(StringUtils.isEmpty(content)){
                        flag = false;
                        textInfo.setUnderLine(1);
                    }else{
                        textInfo.setUnderLine(2);
                    }
                }
                if(flag){
                    // 处理特殊含义的数据
                    content = DocToolUtil.handleSpecialData(content, range);
                }else{
                    content = content.replace(" ", "");
                }

                if(content.equals("&ensp;") && listFlag){
                    continue;
                }
                // 给对象属性赋值
                assignmentTextInfo(textInfo, content, range);
            }else if(imgFlag && paragraphBase instanceof DocPicture){
                DocPicture docPicture  = (DocPicture)paragraphBase;
                try{
                    //判断图片是否为公式
                    if(DocToolUtil.isFormulaImg(docPicture)){
                        gsFlag = true;
                        convertFlag = true;
                    }
                    BufferedImage image = docPicture.getImage();
                    // 判断是否为同一张图片
                    if(imgStr.equals(image.getData().toString())){
                        continue;
                    }
                    imgStr = image.getData().toString();
                    imgNum++;
                    String imgName = filePath.substring(0, filePath.lastIndexOf("/")) +"/" + UUID.randomUUID().toString()+"__"+imgNum + ".png";
                    // 通过工具类实现图片的转化
                    DocToolUtil.downloadImages(docPicture, imgName);

                    imgName = "/profile"+ imgName.substring(imgName.indexOf("/"+ext));
                    textInfo.setImgAddress(imgName);
                    textInfo.setImgWidth(docPicture.getWidth());
                    textInfo.setImgHeight(docPicture.getHeight());
                    // 识别图片为公式
                    if(gsFlag || trim.contains("=")){
                        textInfo.setImgFlag(1);
                    }
                }catch(ClassCastException ex){
                    try {
                        if (convertFlag) {

                            // 实现文件转化
                            String htmlFileName = filePath.substring(0, filePath.lastIndexOf(".")) + ".html";
                            File htmlFile = new File(htmlFileName);
                            if (!htmlFile.exists()) {
                                DocToolUtil.docToHtml(filePath);
                                // 修改主信息的状态
                                DocIndexMapper docIndexMapper = SpringUtils.getBean("docIndexMapper");
                                DocMessageConf docMessageConf = SpringUtils.getBean("docMessageConf");
                                com.ia.aistream.model.operating.entity.DocIndex docIndex = new com.ia.aistream.model.operating.entity.DocIndex();
                                docIndex.setId(fid);
                                String anMsg = "异常%FGF%:" + titleName + "%FGF%" + docMessageConf.getAbnormal();
                                docIndex.setRemark(anMsg);
                                docIndexMapper.updateById(docIndex);
                            }

                            imgNum++;
                            // 去HTML文件中读取数据
                            String imgFileName = filePath.substring(0, filePath.lastIndexOf(".")) + "_images" +
                                    filePath.substring(filePath.lastIndexOf("/"), filePath.lastIndexOf(".")) + "_img" + imgNum + ".png";

                            File file = new File(imgFileName);
                            boolean exists = file.exists();
                            if (exists) {
                                imgFileName = "/profile" + imgFileName.substring(imgFileName.indexOf("/" + ext));
                                textInfo.setImgAddress(imgFileName);
                                textInfo.setImgWidth(docPicture.getWidth());
                                textInfo.setImgHeight(docPicture.getHeight());
                                if (gsFlag || trim.contains("=")) {
                                    textInfo.setImgFlag(1);
                                }
                            } else {
                                log.error("图片转化失败....");
                            }
                        }else{
                            imgNum++;
                            String imgName = filePath.substring(0, filePath.lastIndexOf("/")) +"/" + UUID.randomUUID().toString()+"__"+imgNum + ".wmf";
                            // 通过工具类实现图片的转化
                            DocToolUtil.downloadImages(docPicture, imgName);
                            imgName = WmfToPngUtilTest2.convert(imgName);
                            imgName = "/profile"+ imgName.substring(imgName.indexOf("/"+ext));
                            textInfo.setImgAddress(imgName);
                            textInfo.setImgWidth(docPicture.getWidth());
                            textInfo.setImgHeight(docPicture.getHeight());
                            // 识别图片为公式
                            if(gsFlag || trim.contains("=")){
                                textInfo.setImgFlag(1);
                            }
                        }
                    }catch(Exception e){
                        log.error("转HTML失败....");
                        e.printStackTrace();
                        DocMessageConf docMessageConf = SpringUtils.getBean("docMessageConf");
                        throw new CustomException(titleName + docMessageConf.getError());
                    }
                }
            }else if(paragraphBase instanceof ShapeGroup){
                /****
                 * 处理ShapeGroup类型数据报错
                 * 1、加上大小判断（简单）
                 * 2、加上批量提示（多个位置）
                 */
                DocMessageConf docMessageConf = SpringUtils.getBean("docMessageConf");
                throw new CustomException(titleName + docMessageConf.getError());
            }

            if(textInfo.getContent()!=null || textInfo.getUnderLine()!=null || !StringUtils.isEmpty(textInfo.getListContent())
                    || !StringUtils.isEmpty(textInfo.getImgAddress())){
                textInfoList.add(textInfo);
            }
        }
        paragraphStyle.setPgInfo(pgInfo);
        paragraphStyle.setTextInfoList(textInfoList);
        map.put(DocMapConf.DOC_PARAGRAPH_STYLE.value, paragraphStyle);
        map.put(DocMapConf.DOC_IMG_NUM.value, imgNum);
        return map;
    }

    /***
     * 获取最大的四的行数据
     * @param table
     * @param rows
     * @return
     */
    public static int getColsMax(Table table, int rows){
        //记录4行中的最大列
        int cMax=0;
        if (table.getRows().getCount()>=rows+4) {

            for (int j = rows; j < rows+4; j++) {
                int count = table.getRows().get(j).getCells().getCount();
                if (count > cMax) {
                    cMax = count;
                }
            }
        }else {
            for (int j = rows; j < table.getRows().getCount(); j++) {
                int count = table.getRows().get(j).getCells().getCount();
                if (count > cMax) {
                    cMax = count;
                }
            }
        }
        return cMax;
    }

    /************************************/
    /***
     * 获取段落的页边距
     * @param paragraph
     * @return
     */
    public static double getParagraphMargins(Paragraph paragraph){

        double result = 0.0;
        // 获取段落的对齐方式
        String align = paragraph.getFormat().getHorizontalAlignment().toString();
        if(align.equals("Left")){
            // 获取左对齐的数据
            float leftIndent = paragraph.getFormat().getLeftIndent();
            float firstLineIndent = paragraph.getFormat().getFirstLineIndent();
            float beforeSpacing = paragraph.getFormat().getBeforeSpacing();
            result = leftIndent + firstLineIndent + beforeSpacing;
        }else if(align.equals("Right")){
            // 获取右对齐的数据
            float rightIndent = paragraph.getFormat().getRightIndent();
            float afterSpacing = paragraph.getFormat().getAfterSpacing();
            result = rightIndent + afterSpacing;
        }
        // 保留两位小数
        BigDecimal bg = new BigDecimal(result);
        result = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        if(result<0){
            result = 0.0;
        }
        return result;
    }

    /***
     * 获取表格的最大列
     * @param table
     * @return
     */
    public static int getTableMaxCol(Table table){
        int max = 0;
        for (int r=0; r<table.getRows().getCount(); r++){
            int count = table.getRows().get(r).getCells().getCount();
            if (table.getRows().get(r).getCells().getCount()==1 &&  table.getRows().get(r).getCells().get(0).getParagraphs().get(0).getText().endsWith("附录")){
                break;
            }
            if(count>max){
                max = count;
            }
        }
        return max;
    }
    /******************************************* 私有方法*******************************************/
    /***
     * 判断该内容是不是一级标题
     * @param msg
     * @return
     */
    private static boolean isTitleLevel(String msg){

        String vPattern ="^\\d{1,2}\\.\\s{0,2}.*$";
        Pattern vR = Pattern.compile(vPattern);
        Matcher vM = vR.matcher(msg);
        return vM.matches();
    }


    /****
     * 判断一下是否为二级标题
     * @param msg
     * @return
     */
    public static boolean isTwoLevelTitle(String msg){
        // 获取
        String vPattern ="^\\d{1,2}\\.\\d{1,2}\\.\\d+.*$";
        Pattern vR = Pattern.compile(vPattern);
        Matcher vM = vR.matcher(msg);
        return vM.matches();
    }

    /***
     * p判断是否只有数字
     * @param msg
     * @return
     */
    private static boolean isOnlyNum(String msg){
        String vPattern ="^\\d{1,2}\\.?$";
        Pattern vR = Pattern.compile(vPattern);
        Matcher vM = vR.matcher(msg);
//        if(vM.matches() || msg.equals("0.")){
//            return true;
//        }
        return vM.matches();
    }

    /***
     * p判断是否只有数字
     * @param msg
     * @return
     */
    private static boolean isOnlyNumDian(String msg){
        String vPattern ="^\\d{1,2}.$";
        Pattern vR = Pattern.compile(vPattern);
        Matcher vM = vR.matcher(msg);
        return vM.matches();
    }

    /**
     * 判断是否以数字开头
     * @param msg
     * @return
     */
    private static boolean isStartNum(String msg){
        String vPattern ="^\\d{1,2}\\.\\d*\\s{0,2}.*$";
        Pattern vR = Pattern.compile(vPattern);
        Matcher vM = vR.matcher(msg);
        if(vM.matches() || msg.startsWith("附录")){
            return true;
        }
        return false;
    }

    /***
     * 将颜色转化16进制编码
     * @param num
     * @return
     */
    public static String getColor(int num) {

        char a[]=new char[6];
        int len=a.length-1;
        for(int i=0;i<6;i++) {
            int n=num&15;
            if(n>9)
            {
                a[len]=(char)(n-10+'A');
            }else{
                a[len]=(char)(n+'0');
            }
            len--;
            num=num>>>4;
        }
        StringBuilder str = new StringBuilder();
        str.append("#");
        for(int i=0;i<a.length;i++) {
            str.append(a[i]);
        }
        return str.toString();
    }

    /********************* 处理byte数据转化为16进制 ***********************************/
    /**
     * 字节数组转16进制字符串
     * @param by
     * @return
     */
    public static String bytesToHex(byte by) {
        byte[] bs = {0, 0, 0, by};
        StringBuilder sb = new StringBuilder();
        for (byte b : bs) {
            int high = (b >> 4) & 0x0f;
            int low = b & 0x0f;
            sb.append(HEX_VOCABLE[high]);
            sb.append(HEX_VOCABLE[low]);
        }
        return "\\u" + sb.toString().substring(4);
    }

    /***
     * 将byte转化为int（符号的编码）
     * @param b
     * @return
     */
    public static String bytesToInt(byte b) {
        byte[] src = {b, 0, 0, 0};
        int value;
        value = (int) ((src[0] & 0xFF)
                | ((src[1] & 0xFF) << 8)
                | ((src[2] & 0xFF) << 16)
                | ((src[3] & 0xFF) << 24));
        return "&#" + value + ";";
    }

    /***
     * 实现Visio文件的保存
     * @param docOleObject
     * @param filePath
     * @param ext
     * @return
     */
    public static String saveVisioFile(DocOleObject docOleObject, String filePath, String ext, String titleName) throws Exception {

        String visioPath = "D:/template/";
        String path = filePath.substring(0, filePath.lastIndexOf("/")) +"/";
        String uuid = UUID.randomUUID().toString();
        String visioName =  visioPath + uuid + ".vsd";
        String newVisioName = path + uuid + ".vsd";
        String newImgName = path + uuid + ".png";
        String imgPath = "";

        byte[] nativeData = docOleObject.getNativeData();
        // 获取对象的类型
        String objectType = docOleObject.getObjectType();
        String ver = objectType.substring(objectType.lastIndexOf(".") + 1);

        if(nativeData!=null){
            FileOutputStream fos = null;
//            try{

                int version = Integer.parseInt(ver);
                if(version>=15){
                    visioName = visioName.replace(".vsd", ".vsdx");
                    newVisioName = newVisioName.replace(".vsd", "vsdx");
                }
//                else if(version<9){
//                    throw new CustomException(titleName + "Visio文件版本异常，请更新后重试...");
//                }
                // 实现文件保存
                File file = new File(visioName);
                fos = new FileOutputStream(file);
                fos.write(nativeData);
                fos.close();
                imgPath = PdfToPngUtil.visioToPng(visioName);
                // 实现文件的下载
                File fromVisioFile = new File(visioName);
                File toVisioFile = new File(newVisioName);
                FileUtil.copyFile(fromVisioFile, toVisioFile);

                File fromImgFile = new File(imgPath);
                File toImgName = new File(newImgName);
                FileUtil.copyFile(fromImgFile, toImgName);
        }
        newVisioName = "/profile"+ newVisioName.substring(newVisioName.indexOf("/"+ext));
        newImgName = "/profile" + newImgName.substring(newImgName.indexOf("/"+ext));
//        imgPath = imgPath.replace("\\", "/");
//        visioName = visioName.replace("\\", "/");

        return newVisioName + "%F%G%F" + newImgName;
    }

    /***
     * 实现TextInfo对象赋值
     * @param textInfo 赋值对象
     * @param content 文本内容
     * @param range 文本对象
     */
    public static void assignmentTextInfo(TextInfo textInfo, String content, TextRange range){

        // 内容赋值
        textInfo.setContent(content);
        // 记录字体是否加粗
        textInfo.setBold(range.getCharacterFormat().getBold());
        // 设置文字字体
//        textInfo.setFontName(range.getCharacterFormat().getFontNameFarEast());
        textInfo.setFontName(range.getCharacterFormat().getFontName());
        // 设置字号
        textInfo.setFontSize(range.getCharacterFormat().getFontSize());
        // 设置文字颜色
        textInfo.setFontColor(getColor(range.getCharacterFormat().getTextColor().getRGB()));
        // 设置背景颜色
        String color = getColor(range.getCharacterFormat().getHighlightColor().getRGB());
        if(!color.equals("#000000")){
            textInfo.setBgColor(color);
        }
    }

    /***
     * 处理特殊字符对象赋值
     * @param symbol
     * @return
     */
    public static TextInfo assignmentSymbol(Symbol symbol){

        TextInfo textInfo = new TextInfo();
        String charFontName = symbol.getFontName();
        byte characterCode = symbol.getCharacterCode();

        textInfo.setContent(bytesToInt(characterCode));
        textInfo.setFontName(charFontName);
        textInfo.setFontSize(symbol.getCharacterFormat().getFontSize());
        return textInfo;
    }



}
